//类组件实现todolist
/*
    总结：
        列表渲染：在react中，通过map方法实现。因为map方法，可以对数据进行加工，返回新的数据(jsx)
*/
import {Component} from "react";
class DemoA extends Component{
    constructor(props){
        super(props)
        this.state={
            todo:"",
            list:[]
        }
    }
    getTodo(e){
        this.setState({
            todo:e.target.value
        })
    }
    confirm(){
        if(!this.state.todo.trim()){
            alert('必须输入内容');
            return;
        }
        this.setState(state=>({
            list:[...state.list,{id:Date.now(),task:state.todo}]
        }))
        this.setState({
            todo:''
        })
    }
    addByEnter(e){
        if(e.keyCode===13){
            this.confirm();
        }
    }
    delTodo(id){
        this.setState(state=>({
            list:state.list.filter(item=>item.id!=id)
        }))
    }
    render(){
        let {todo,list} = this.state;
        return(
            <div>
                <div>
                    <input 
                        type="text" 
                        value={todo}
                        onChange={e=>this.getTodo(e)}
                        onKeyUp={e=>this.addByEnter(e)}
                        style={{display:"inline-block",height:"40px",padding:"0"}}
                    />
                    <button 
                        onClick={(e)=>this.confirm(e)}
                        style={{display:"inline-block",width:"40px",height:"44px",padding:"0",verticalAlign:"middle"}}
                    >添加</button>
                </div>
                <div>
                    {
                        list.map((item,index,arr)=>(
                            <div key={item.id}>
                                <span>{item.id}</span>--<span>{item.task}</span>
                                <button onClick={()=>this.delTodo(item.id)}>删除</button>
                            </div>
                        ))
                    }
                </div>
            </div>
        )
    }
}
export default DemoA;